<?php

namespace app\api\controller\admin;

use app\admin\model\AuthGroup;
use app\common\controller\Api;
use fast\Tree;
use think\Db;

/**
 * 接口
 */
class Admingroup extends Api
{





    protected $noNeedLogin = ['*'];
    //无需要权限判断的方法
    protected $noNeedRight = ['*'];







    public function index()
    {
        $this->success('请求成功66555index');
    }

    /**
     * 查看
     *
     */
    public function gindex()
    {

        $params = $this->request->param();
        $action =$params['action'];
        if($action=='apiindex'){
            $data= self::apiindex();
            return $data;
        }elseif ($action=='apiadd'){
            self::apiadd();
        }elseif ($action=='apiedit'){
            self::apiedit();
        }elseif ($action=='apidel'){
            self::apidel();
        }elseif ($action=='apiroletreelist'){
            self::roletreelist();
        }elseif ($action=='apiroletreexlk'){
            self::roletreexlk();
        }elseif ($action=='apieditget'){
            self::apieditget();
        }elseif ($action=='apitreeleft'){
            self::treeleft();
        }



    }

    /**
     * 查看
     */
    public function apiindex()
    {

        $params = $this->request->param();
        $pageSize =$params['pageSize'];
        $pageNum =$params['pageNum'];
        $name =isset($params['name']) ? $params['name'] : '';
        $sort=isset($params['sort']) ? $params['sort'] : 'id';
        $order=isset($params['order']) ? $params['order'] : 'desc';
        $systemFlag=isset($params['systemFlag']) ? $params['systemFlag'] : '';
        $where=[];
        if ($systemFlag){
            $where['id']  = array('like',  '%'.$systemFlag."%");
        }
        if ($name){
            $where['username']  = array('like',  '%'.$name."%");
        }
//        $pageNum=1;
//        $pageSize=1;
//        $sort='id';
//        $order='desc';
////halt($where);
//        $where['id']  = 1;
        $pageNum=($pageNum-1)*$pageSize;
        $list = Db::table('fa_g_auth_group')
            ->where($where)
            ->order($sort, $order)
            ->limit($pageNum,$pageSize)
            ->select();
        $total= Db::table('fa_g_auth_group')
            ->where($where)
            ->order($sort, $order)
            ->limit(1,2)
            ->count();
        foreach ($list as $k => &$v) {
            $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
//            $v['groups'] = implode(',', array_keys($groups));
//            $v['groups_text'] = implode(',', array_values($groups));
        }
        unset($v);
        $result = array("total" => $total, "rows" => $list);
//        $this->success('成功',$result);
        return json($result);

    }
    /**
     * add
     */
    public function apiadd()
    {
        $post = $this->request->post();
        unset($post['action']);
        $post['createtime']=time();
        $list=Db::table('fa_g_auth_group')->insertGetId($post);

        $this->success($list);

    }
    /**
     * up
     */

    public function apiedit()
    {
        $post = $this->request->post();
        unset($post['action']);
//        halt($post);
        $post['updatetime']=time();
        $list=Db::table('fa_g_auth_group')->update($post);
        $this->success($list);

    }
    public function apieditget()
    {
        $post = $this->request->post();
        unset($post['action']);
//        halt($post);
        $post['updatetime']=time();
        $list=Db::table('fa_g_auth_group')
            ->where('id',$post['id'])
            ->update($post);
        $this->success($list);

    }
    public function apidel()
    {
        $post = $this->request->post();
        unset($post['action']);
        $list=Db::table('fa_g_auth_group')->delete($post);
        $this->success($list);
    }
//角色组树
    public function tree()
    {
        $post = $this->request->post();
        unset($post['action']);
        $list=Db::table('fa_g_auth_group')->where('id',$post['id'])->select();

        $aa=self::roletree();
        halt(6);
        halt($aa);


Tree::instance()->init();
$groupList = [];


    $groups = Db::table('fa_g_auth_group')->where('id',$post['id'])->select();

        $groupIds = [];
    foreach ($groups as $m => $n) {
        halt($n);
        if (in_array($n['id'], $groupIds) || in_array($n['pid'], $groupIds)) {
            continue;
        }
        halt($groupIds);
        $groupList = array_merge($groupList, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
        foreach ($groupList as $index => $item) {
            $groupIds[] = $item['id'];
        }
    }

$groupName = [];
foreach ($groupList as $k => $v) {
    $groupName[$v['id']] = $v['name'];
}

$this->grouplist = $groupList;
$this->groupdata = $groupName;
        $this->success($groupName);


    }


    /**
     * 读取角色权限树
     *
     * @internal
     */
    public function roletree()
    {


        $id = $this->request->post("id");
        $pid = $this->request->post("pid");
        $parentGroupModel = Db::table('fa_g_auth_group')->where('id',$pid)->find();
        $currentGroupModel = null;
//        $ruleList = collection(Db::table('fa_g_auth_rule')->order('id', 'asc')->select())->toArray();
//
//        $groupTree = new Tree();
//        //当前所有正常规则列表
//        $groupTree->init($ruleList);
//        halt($groupTree);
        if ($id) {
            $currentGroupModel =Db::table('fa_g_auth_group')->where('id',$id)->find();
        }
        if (($pid || $parentGroupModel) && (!$id || $currentGroupModel)) {
            $id = $id ? $id : null;

            $ruleList = collection(Db::table('fa_g_auth_rule')->order('weigh', 'desc')->order('id', 'asc')->select())->toArray();
            //读取父类角色所有节点列表
            $parentRuleList = [];
            if (in_array('*', explode(',', $parentGroupModel['rules']))) {
                $parentRuleList = $ruleList;
            } else {
                $parentRuleIds = explode(',', $parentGroupModel['rules']);
                foreach ($ruleList as $k => $v) {
                    if (in_array($v['id'], $parentRuleIds)) {
                        $parentRuleList[] = $v;
                    }
                }
            }

            $ruleTree = new Tree();

            $groupTree = new Tree();
            //当前所有正常规则列表
            $ruleTree->init($parentRuleList);
            //角色组列表
            $groupTree->init(collection(Db::table('fa_g_auth_group')->select())->toArray());

            //读取当前角色下规则ID集合
            $adminRuleIds = $groupTree;
            //是否是超级管理员
            $superadmin = $groupTree;
            //当前拥有的规则ID集合
            $currentRuleIds = $id ? explode(',', $parentGroupModel['rules']) : [];

            if (!$id || !in_array($pid, $groupTree->getChildrenIds($id, true))) {
                $parentRuleList = $ruleTree->getTreeList($ruleTree->getTreeArray(0), 'name');
                $hasChildrens = [];
                foreach ($parentRuleList as $k => $v) {
                    if ($v['haschild']) {
                        $hasChildrens[] = $v['id'];
                    }
                }
                $parentRuleIds = array_map(function ($item) {
                    return $item['id'];
                }, $parentRuleList);
                $nodeList = [];
                foreach ($parentRuleList as $k => $v) {
                    if (!$superadmin && !in_array($v['id'], $adminRuleIds)) {
                        continue;
                    }
                    if ($v['pid'] && !in_array($v['pid'], $parentRuleIds)) {
                        continue;
                    }
                    $state = array('selected' => in_array($v['id'], $currentRuleIds) && !in_array($v['id'], $hasChildrens));
                    $nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
                }

                $this->success('', null, $nodeList);
            } else {
                $this->error('不能将父改为子');
            }
        } else {
            $this->error('未找到群组');
        }
    }

    /**
     * 读取角色权限树--列表
     *
     * @internal
     */
    public function roletreelist()
    {
        $id = $this->request->post("id");
        $pid = $this->request->post("pid");
        $parentGroupModel = Db::table('fa_g_auth_group')->where('id',$pid)->find();
            $id = $id ? $id : null;
            $ruleList = collection(Db::table('fa_g_auth_rule')->order('weigh', 'desc')->order('id', 'asc')->select())->toArray();
            //读取父类角色所有节点列表
                $parentRuleList = $ruleList;
            $ruleTree = new Tree();
            $groupTree = new Tree();
            //当前所有正常规则列表
            $ruleTree->init($parentRuleList);
            //角色组列表
            $groupTree->init(collection(Db::table('fa_g_auth_group')->select())->toArray());
            //当前拥有的规则ID集合
            $currentRuleIds = $id ? explode(',', $parentGroupModel['rules']) : [];
        $nodeList=  $ruleTree->getTreeArrayzdy(0);
                $this->success('cg', $nodeList);

    }

    /**
     * 读取角色权限树--列表---下拉框
     *
     * @internal
     */
    public function roletreexlk()
    {
        $parentGroupModel = Db::table('fa_g_auth_group')->select();
        $this->success('下拉框', $parentGroupModel);
    }
    /**
     * 读取角色权限树--列表--用于登录的时候-sidebar.vue 显示左侧列表
     *
     * @internal
     */
    public function treeleft()
    {

        $ruleList = Db::table('fa_g_auth_rule')->order('weigh', 'desc')->order('id', 'asc')->field('id,pid,id as permiss,icon,index,title')->select();

        //读取父类角色所有节点列表
        $parentRuleList = $ruleList;
        $ruleTree = new Tree();
        //当前所有正常规则列表
        $ruleTree->init($parentRuleList);
//        halt($ruleTree);
        //当前拥有的规则ID集合
//        $currentRuleIds = $id ? explode(',', $parentGroupModel['rules']) : [];
//        $nodeList=  $ruleTree->getTreeArrayzdy(0);
        $nodeList=  $ruleTree->getTreeArrayzdyleft(0);
        $this->success('cg', $nodeList);





    }



}
